package com.sgb.kjwl.view.ui.activity.packers;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.aspectj.login.LoginCheck;
import com.sgb.kjwl.databinding.FragmentPackerChangeBinding;
import com.sgb.kjwl.model.entity.packers.TeamDetailEntity;
import com.sgb.kjwl.utils.NumberConstant;
import com.sgb.kjwl.utils.WebJsConstants;
import com.sgb.kjwl.view.ui.activity.WebViewX5Fragment;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickInquireByLetterActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.viewmodel.packers.TeamDetailViewModel;
import com.sgb.link.router.PathTeam;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.ycbjie.webviewlib.base.X5WebChromeClient;

/**
 * @author younghow
 * @date 2021/9/6
 * description:工队详情
 */
@Route(path = PathTeam.TeamDetailActivity)
public class TeamDetailActivity extends AppActivity {
    FragmentPackerChangeBinding mBind;
    private String mUserNo;
    private int mCompanyType;
    private String mMomentNo;
    private boolean mIsFollow = false;
    private String mImId;
    private TeamDetailViewModel mViewModel;
    private String no;
    private boolean mIsCompany;
    private String mCompanyNo;
    private String mCompanyName;
    private String mMomentCompanyNo;
    private String mRelevance;

    @Override
    protected void initView() {
        mBind = DataBindingUtil.setContentView(this, R.layout.fragment_packer_change);

        mBind.setLifecycleOwner(this);
        mViewModel = new ViewModelProvider(this).get(TeamDetailViewModel.class);

        no = getIntent().getStringExtra("no");
        String url = getIntent().getStringExtra("url");

        mBind.tvAskPrice.setOnClickListener(this);
        mBind.linAttention.setOnClickListener(this);
        mBind.linHanxun.setOnClickListener(this);
        mBind.linIm.setOnClickListener(this);
        mBind.linInviteJoin.setOnClickListener(this);
        mBind.linRequestJoin.setOnClickListener(this);

        mViewModel.getTeamDetail(no);

        mBind.wvLaborService.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mBind.wvLaborService.getSettings().setDomStorageEnabled(true);
        mBind.wvLaborService.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        mBind.wvLaborService.getSettings().setAppCacheEnabled(true);
        X5WebChromeClient mChromeClient = new X5WebChromeClient(mBind.wvLaborService, TeamDetailActivity.this) {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                Log.e("WebViewX5Activity", newProgress + "");
            }
        };
        mBind.wvLaborService.setWebChromeClient(mChromeClient);
        mBind.wvLaborService.loadUrl(url);
        mBind.wvLaborService.registerHandler(WebJsConstants.GO_TO_WEBSITE, (data, function) -> {
            try {
                WebViewX5Fragment.WebsiteEntity entity = new Gson().fromJson(data, WebViewX5Fragment.WebsiteEntity.class);
                if (TextUtils.isEmpty(entity.siteNo)) {
                    MToast.showToast(this, "网站编号为空");
                    return;
                }
                WebsiteInfoActivity.start(this, entity.siteNo, entity.siteType);
            } catch (Exception e) {
                MLog.d("website", "H5传参错误");
            }
        });

        initLiveData();
    }

    private void initLiveData() {
        mViewModel.mTeamDetailLiveData.observe(this, teamDetailEntity -> {
            if (teamDetailEntity != null && !TextUtils.isEmpty(teamDetailEntity.getUserNo())) {
                mBind.llLabelService.setVisibility(View.VISIBLE);
                mIsFollow = teamDetailEntity.isFocus();
                mMomentNo = teamDetailEntity.getUserNo();
                mIsCompany = teamDetailEntity.getIsCompany() == 1;
                mCompanyNo = teamDetailEntity.getCompanyNo();
                mCompanyName = teamDetailEntity.getCompanyName();
                mImId = teamDetailEntity.getImId();

                if (!mIsFollow) {
                    mBind.ivAttention.setImageResource(R.mipmap.img_gary_heart);
                    mBind.tvAttention.setTextColor(ContextCompat.getColor(TeamDetailActivity.this, R.color.color_666666));
                    mBind.tvAttention.setText("关注");
                } else {
                    mBind.ivAttention.setImageResource(R.mipmap.gz_orange);
                    mBind.tvAttention.setTextColor(ContextCompat.getColor(TeamDetailActivity.this, R.color.color_EF4033));
                    mBind.tvAttention.setText("已关注");
                }
            }
        });

        mViewModel.mImLiveData.observe(this, this::buildSingleTalking);
        mViewModel.mImbLiveData.observe(this, this::buildSingleTalking);

        mViewModel.mFollowSuccessLiveData.observe(this, aBoolean -> {
            if (!aBoolean){
                NumberConstant.sIsBackForTeam = 1;
                MToast.showToast(TeamDetailActivity.this,"该工队已删除，请重新选择");
                finish();
            }else {
                if (!mIsFollow) {
                    mBind.ivAttention.setImageResource(R.mipmap.gz_orange_no_select);
                    mBind.tvAttention.setTextColor(ContextCompat.getColor(TeamDetailActivity.this, R.color.color_666666));
                    mBind.tvAttention.setText("关注");
                } else {
                    mBind.ivAttention.setImageResource(R.mipmap.gz_orange);
                    mBind.tvAttention.setTextColor(ContextCompat.getColor(TeamDetailActivity.this, R.color.color_EF4033));
                    mBind.tvAttention.setText("已关注");
                }
            }
        });
    }

    @Override
    public void onMultiClick(View v) {
        super.onMultiClick(v);
        int id = v.getId();
        if (id == R.id.tv_ask_price) {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(getActivity(), false);
                return;
            }

            MToast.showToast(this, "功能开发中");
        } else if (id == R.id.lin_attention) {
            followCheck();
        } else if (id == R.id.lin_im) {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(getActivity(), false);
            } else {
                if (mMomentNo.equals(mUserNo)) {
                    MToast.showToast(this, "不能和自己交流");
                } else {
                    if (!mIsCompany) {
                        MToast.showToast(this, "该信息为个人用户发布，当前无法交流");
                        return;
                    }

                    if (!TextUtils.isEmpty(mImId)) {
                        mViewModel.findCustomerServiceImAccount(mImId);
                    } else {
                        MToast.showToast(this, "未设置客服人员，无法交流！");
                    }
                }
            }
        } else if (id == R.id.lin_hanxun) {
            letter();
        } else if (id == R.id.lin_request_join) {
            request();
        } else if (id == R.id.lin_invite_join) {
            invite();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mUserNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        mCompanyType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        mRelevance = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.RELEVANCE,"");
        mMomentCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
    }

    @LoginCheck(needRealName = true)
    public void followCheck(){
        if (mMomentNo.equals(mUserNo)) {
            MToast.showToast(this, "不能关注自己发布的工队");
        } else {
            mIsFollow = !mIsFollow;
            mViewModel.followForTeam(no, "1", mIsFollow);
        }
    }

    @LoginCheck(needRealName = true)
    public void letter(){
        if (mMomentNo.equals(mUserNo)) {
            MToast.showToast(this, "不能给自己发送函询");
        } else {
            PickInquireByLetterActivity.start(this, no, "team", "", "", "3", "", "laborWorkDetail");
        }
    }

    @LoginCheck(needRealName = true)
    public void request(){
        if (!mIsCompany){
            MToast.showToast(this, "该信息为个人用户发布，当前无法申请加盟");
            return;
        }

        if (mCompanyType == 0){
            if ("0".equals(mRelevance)){
                MToast.showToast(this, "您暂未认证企业，当前无法申请加盟");
            }else {
                ActivityJump.startActivity(PathTeam.TeamApplyJoinActivity, Pair.create(RouterKey.NO,mCompanyNo),Pair.create(RouterKey.NAME,mCompanyName));
            }
        }else if (mCompanyType > 1){
            MToast.showToast(this, "请前往用户中心将身份切换为个人或企业才能申请加盟");
        }else if (mCompanyType == 1){
            if (mCompanyNo.equals(mMomentCompanyNo)) {
                MToast.showToast(this, "不能申请加盟自己的企业");
            } else {
                ActivityJump.startActivity(PathTeam.TeamApplyJoinActivity, Pair.create(RouterKey.NO,mCompanyNo),Pair.create(RouterKey.NAME,mCompanyName));
            }
        }
    }

    @LoginCheck(needRealName = true)
    public void invite(){
        if (!mIsCompany){
            MToast.showToast(this, "该信息为个人用户发布，当前无法邀请加盟");
            return;
        }

        if (mCompanyType == 0){
            if ("0".equals(mRelevance)) {
                MToast.showToast(this, "您暂未认证企业，当前无法邀请加盟");
            }else {
                ActivityJump.startActivity(PathTeam.TeamInviteJoinActivity, Pair.create(RouterKey.NO,mCompanyNo),Pair.create(RouterKey.NAME,mCompanyName));
            }
        }else if (mCompanyType == 2 || mCompanyType == 3){
            MToast.showToast(this, "请前往用户中心将身份切换为个人或企业才能邀请加盟");
        } else if (mCompanyType == 1) {
            if (mCompanyNo.equals(mMomentCompanyNo)) {
                MToast.showToast(this, "不能邀请自己的企业加盟");
            }else {
                ActivityJump.startActivity(PathTeam.TeamInviteJoinActivity, Pair.create(RouterKey.NO,mCompanyNo),Pair.create(RouterKey.NAME,mCompanyName));
            }
        }
    }
}